﻿using DMS.Common.Model.Result;
using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SqlSugar.Template.IService;
using SqlSugar.Template.IService.Param;
using SqlSugar.Template.Service;
using System.IO;
using SqlSugar.Template.Models;
using System.Linq;
using Microsoft.AspNetCore.Authorization;

namespace BookApi.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class StockController : ControllerBase
    {

        private readonly IStockLstService stockLstService;
        public StockController( IStockLstService stockLstService)
        {
            this.stockLstService = stockLstService;
        }

        [HttpPost("Add")]
        [Authorize]
        public async Task<ResponseResult> AddAsync(AddStockLstParam param)
        {
            //添加子列表  
            return await stockLstService.Add(param);            
        }

        [HttpPost("Update")]
        [Authorize]
        public async Task<ResponseResult> UpdateAsync(EditStockLstParam param)
        { 
            return await stockLstService.UpdateAsync(param);
        }

        /// <summary>
        /// 上传股票图片
        /// </summary>
        /// <param name="file"></param>
        /// <param name="bookID">雪花ID</param>
        /// <returns></returns>
        [HttpPost("upload")]
        [Authorize]
        public async Task<IActionResult> UploadImage(IFormFile file, long bookID, bool isUpdate)
        {
            var image = file;
            var fileName = bookID+ file.FileName.Substring(file.FileName.LastIndexOf("."));
            var filePath = Path.Combine(Directory.GetCurrentDirectory(), "uploads", fileName);
            var directory = Path.GetDirectoryName(filePath);
            if (!Directory.Exists(directory))
                Directory.CreateDirectory(directory);
            StockLst stock = new()
            {
                BookId = bookID,
                Picture = "/api/uploads/" + fileName,
            };
            if (isUpdate)
            {
                await stockLstService.UpdateByIdAsync(stock);
            }
           
            using (var stream = new FileStream(filePath, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            return Ok("/api/uploads/" + fileName);
        }

        /// <summary>
        /// 删除上传文件
        /// </summary>
        /// <param name="imageUrl"></param>
        /// <returns></returns>
        [HttpPost("DeleteFile")]
        [Authorize]
        public async Task<ResponseResult> DeleteFileAsync(string imageUrl)
        {
            var imageName = imageUrl.Substring(imageUrl.LastIndexOf("/") + 1);
            DirectoryInfo directoryInfo = new DirectoryInfo(Path.Combine(Directory.GetCurrentDirectory(), "uploads"));
            // 获取当前目录及其子目录中的所有文件（递归）
            FileInfo[] files = directoryInfo.GetFiles("*.*", SearchOption.AllDirectories).Where(it=>it.Name== imageName).ToArray();
            var filePath = files.First().FullName;
            // 删除文件
            System.IO. File.Delete(filePath);       
            var res = await stockLstService.DeleteFileAsync(imageUrl);
            return res;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="bookID"></param>
        /// <returns></returns>
        [HttpPost("Delete")]
        [Authorize]
        public async Task<ResponseResult> DeleteAsync(long bookID)
        {
            var result = await stockLstService.DeleteAsync(bookID);
            return result;
        }
    }
}
